import dynamic from 'next/dynamic'
import UserLayout from '@c/user/user-layout'
import Button from '@c/button'
import { useEffect, useState } from 'react'
import styles from './index.module.scss'
import cm from 'classnames'
import EventBus from '@/utils/emitter'

const ImportBuild = dynamic(() => import('@c/user/build/import-build'))
const PublishBuild = dynamic(() => import('@c/user/build/publish-build'))
const ImportBuildManage = dynamic(() => import('@c/user/build/import-build-manage'))
const Null = dynamic(() => import('@c/user/null'))

const Index = () => {
  const [tabType, setTabType] = useState('publish')
  const [currChannel, setCurrChannel] = useState({})
  const [loginCode, setLogin] = useState(0) // 0初始1已登录2未登录
  useEffect(() => {
    setLogin(!localStorage.getItem('token') ? 2 : 1)
    EventBus.on('zj', type => {
      setTabType(type)
    })
    return () => {
      sessionStorage.setItem('lastPage', true)
      EventBus.offAll('zj')
    }
  }, [])

  const openDialog = () => {
    EventBus.emit(tabType)
  }

  // 已登录DOM
  const LoginDom = (
    <>
      {tabType !== 'import-manage' ? (
        <>
          <div className={styles.itemBox}>
            <div className={cm(styles.itemText, 'hideWhenPc')}>自建频道</div>
            <div className={styles.itemsTab}>
              <span
                onClick={() => setTabType('publish')}
                className={cm(styles.itemsTabItem, tabType === 'publish' ? styles.itemsTabItemActive : '')}
              >
                发布自建
              </span>
              <span
                onClick={() => setTabType('import')}
                className={cm(styles.itemsTabItem, tabType === 'import' ? styles.itemsTabItemActive : '')}
              >
                引用自建
              </span>
            </div>
            <Button className={cm(styles.btnAdd, 'hideWhenPhone')} onClick={openDialog}>
              <img loading="lazy" src="/images/h-add.png" alt="添加" />
              <span>添加</span>
            </Button>
          </div>
          {tabType === 'publish' ? <PublishBuild /> : null}
          {tabType === 'import' ? <ImportBuild setChannel={setCurrChannel} /> : null}
        </>
      ) : (
        <ImportBuildManage channel={currChannel} />
      )}
    </>
  )
  // 未登录DOM
  const NotLogin = <Null loginTxt="登录后才能查看或添加自建频道哦~" style={{ marginTop: 120 }} />
  return (
    <UserLayout type="zj">
      <div className={styles.items}>
        {loginCode === 1 ? LoginDom : null}
        {loginCode === 2 ? NotLogin : null}
      </div>
    </UserLayout>
  )
}

export default Index

export async function getServerSideProps() {
  return {
    props: {
      layoutProps: {
        noSomeMetaInfo: false,
        url: '/history',
        title: '自建频道管理 - 星视界',
        desc: '星视界是一款海外华人电视直播和影视大全，免费观看中文电视节目和影视内容。在这里，您可以畅享中文直播内容及海量影视资源，涵盖香港、台湾、新马、大陆频道直播，以及电视剧、电影、综艺、动漫节目点播等，尽情享受视听盛宴。'
      }
    }
  }
}
